import {createRouter, createWebHistory, Router, RouteRecordRaw} from 'vue-router';
import {MenuOut} from '@/classes/dto/System';

//================================
const menus: MenuOut[] = [
    {
        id: '1',
        title: '首页',
        type: 0,
        path: '/main/index'
    },
    {
        id: '2',
        title: '域名管理',
        type: 0,
        path: '/domain/index',
        children: [
            {
                id: '21',
                title: '域名',
                type: 0,
                path: '/domain/list'
            },
            {
                id: '22',
                title: '记录解析',
                type: 1,
                path: '/domain/resolve',

            }
        ]
    }
]


const modules = import.meta.glob('../views/*/*.vue');

const routes: RouteRecordRaw[] = [
    {
        path: '/', redirect: {name: 'login'},
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login.vue'),
    }, {
        path: '/layout',
        name: 'layout',
        component: () => import('@/views/index.vue'),
        children: []
    },
]


console.info('===routes=====>', JSON.stringify(routes))

const router: Router = createRouter({
    history: createWebHistory(),
    routes
});

function addRoute(menus: MenuOut[], routers: RouteRecordRaw[]) {

    menus.forEach((menu, index) => {


        const roure: RouteRecordRaw = {

            path: menu.path || '/' + Date.now(),

            name: (menu.path || '_').split('/').filter(v => v.trim()).map(v => v).join('_'),

            component: modules[`../views${menu.path}.vue`] || import('@/views/index.vue'),

            meta: {
                sort: menu.sort || index,
                // icon: menu.icon,
                title: menu.title,

                type: menu.type
            },
        }

        if (menu.children && menu.children.length) {

            roure.children = roure.children || []

            addRoute(menu.children, roure.children);

        }
        routers.push(roure);
    });
}

let isLoad = false;

router.beforeEach((to, from, next) => {

    console.info('beforeEach==>', isLoad)

    if (isLoad) {
        next()

        return;
    }

    routes[2].children = routes[2].children || []

    addRoute(menus, routes[2].children)

    router.addRoute(routes[2])

    isLoad = true

    console.info('==routes==>', JSON.stringify(routes))

    next(to)

})


export default router